import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/generated/assets.dart';
import 'package:flutter_base/pages/test_detail/widgets/test_card_base.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_base/pages/test_detail/model/model_test_detail.dart';
import 'package:flutter_base/widgets/image/auto_image.dart';
import 'package:flutter_svg/flutter_svg.dart';

class TestGrowthPathBlock extends StatelessWidget {
  final ModelTestDetail? testDetail;
  final int currentStage;

  final List<String> items;

  const TestGrowthPathBlock({
    super.key,
    this.testDetail,
    this.currentStage = 4,
    required this.items,
  });

  @override
  Widget build(BuildContext context) {
    return TestCardBase(
      gradient: const LinearGradient(colors: [
        AppColor.colorE5FFFB,
        Colors.white,
      ], begin: Alignment.topCenter, end: Alignment.bottomCenter),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题部分
          Text(
            'Growth Path',
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF0C0A09),
              letterSpacing: 0.14,
            ),
          ),
          SizedBox(height: 4.w),
          Text(
            'Your Psychological Growth Stage',
            style: TextStyle(
              fontSize: 12.sp,
              color: const Color(0xFF7F909F),
            ),
          ),
          // SizedBox(height: 12.w),

          // 进度环图
          SizedBox(
            height: 180.w,
            width: double.infinity,
            child: Stack(
              alignment: Alignment.center,
              children: [
                // 半圆环形进度图
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  child: SemiCircleProgressWidget(
                    currentStage: currentStage,
                    totalStages: items.length,
                    size: Size(310.w, 180.w),
                  ),
                ),
                // 中心文字 - 放置在半圆内
                Positioned(
                  // top: 60.w,
                  bottom: 10.w,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        items[currentStage],
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w700,
                          color: const Color(0xFF0D0D12),
                        ),
                      ),
                      SizedBox(height: 4.w),
                      Text(
                        'Current Stage: $currentStage',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: const Color(0xFFADB5C2),
                          letterSpacing: 0.2,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 24.w),

          SizedBox(
            width: double.infinity,
            child: Wrap(
              spacing: 24.w,
              runSpacing: 24.w,
              children: items.map((item) {
                return _buildStageItem(
                  item,
                  'Stage ${items.indexOf(item)}',
                  _getStageColor(items.indexOf(item)),
                  isActive: currentStage >= 1,
                );
              }).toList(),
            ),
          ),

          // // 第一行阶段
          // Row(
          //   children: [
          //     Expanded(
          //       child: _buildStageItem(
          //         'Self-awareness',
          //         'Stage 1',
          //         _getStageColor(1),
          //         isActive: currentStage >= 1,
          //       ),
          //     ),
          //     SizedBox(width: 24.w),
          //     Expanded(
          //       child: _buildStageItem(
          //         'Skill Development',
          //         'Stage 2',
          //         _getStageColor(2),
          //         isActive: currentStage >= 2,
          //       ),
          //     ),
          //   ],
          // ),
          // SizedBox(height: 24.w),
          //
          // // 第二行阶段
          // Row(
          //   children: [
          //     Expanded(
          //       child: _buildStageItem(
          //         'Practical application',
          //         'Stage 3',
          //         _getStageColor(3),
          //         isActive: currentStage >= 3,
          //       ),
          //     ),
          //     SizedBox(width: 24.w),
          //     Expanded(
          //       child: _buildStageItem(
          //         'Continuous optimization',
          //         'Stage 4',
          //         _getStageColor(4),
          //         isActive: currentStage >= 4,
          //       ),
          //     ),
          //   ],
          // ),
          // SizedBox(height: 24.w),
          //
          // // 第三行阶段
          // _buildStageItem(
          //   'Influencing others',
          //   'Stage 5',
          //   _getStageColor(5),
          //   isFullWidth: true,
          //   isActive: currentStage >= 5,
          // ),
        ],
      ),
    );
  }

  // 获取阶段颜色
  Color _getStageColor(int stage) {
    stage = (stage + 1) % 5;
    switch (stage) {
      case 1:
        return const Color(0xFF90FF5D); // 亮绿色
      case 2:
        return const Color(0xFF39DD72); // 深绿色
      case 3:
        return const Color(0xFF29DDED); // 青色
      case 4:
        return const Color(0xFF2C8BFF); // 蓝色
      case 5:
        return const Color(0xFF7550E5); // 紫色
      default:
        return const Color(0xFFECF2FC); // 灰色
    }
  }

  Widget _buildStageItem(String title, String stage, Color dotColor,
      {bool isFullWidth = false, bool isActive = true}) {
    // 非激活状态使用灰色
    final Color textColor = isActive ? dotColor : const Color(0xFFECF2FC);

    return SizedBox(
      height: 47.w,
      width: 143.w,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: 12.sp,
              color: const Color(0xFF7F909F),
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
          Row(
            children: [
              Container(
                width: 8.w,
                height: 8.w,
                decoration: BoxDecoration(
                  color: textColor,
                  shape: BoxShape.circle,
                ),
              ),
              SizedBox(width: 8.w),
              Text(
                stage,
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w700,
                  color: AppColor.color0C0A09,
                ),
              ),
            ],
          ),
          SizedBox(height: 4.w),
        ],
      ),
    );
  }
}

class SemiCircleProgressWidget extends StatelessWidget {
  final int currentStage;
  final int totalStages;
  final Size size;
  final int totalSvgCount = 23; // 固定的SVG总数

  const SemiCircleProgressWidget({
    Key? key,
    required this.currentStage,
    this.totalStages = 5,
    required this.size,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 使用与原CustomPainter相同的逻辑，但使用Widget而不是Canvas绘制
    final double centerX = size.width / 2;
    // 减小半径，让图标更靠近中心点
    final double radius = size.width / 2 - 20.w;

    // 未激活状态的颜色
    final Color inactiveColor = const Color(0xFFECF2FC);

    // 每个SVG图标的大小
    final double svgWidth = 18.w;
    final double svgHeight = 36.w;

    // 定义颜色数组（从左到右）
    final List<Color> stageColors = [
      const Color(0xFF7550E5), // 紫色（左侧）
      const Color(0xFF2C8BFF), // 蓝色
      const Color(0xFF29DDED), // 青色
      const Color(0xFF39DD72), // 深绿色
      const Color(0xFF90FF5D), // 亮绿色（右侧）
      const Color(0xFFE667AF), // 粉红色
      const Color(0xFFFF8A65), // 橙色
      const Color(0xFFFFC107), // 琥珀色
      const Color(0xFF9C27B0), // 深紫色
      const Color(0xFF3F51B5), // 靛蓝色
    ];

    // 计算每个阶段应该分配的SVG数量
    List<int> svgDistribution =
        _calculateSvgDistribution(totalStages, totalSvgCount);

    // 计算每个阶段的起始SVG索引
    List<int> stageStartIndices = [0];
    int sum = 0;
    for (int i = 0; i < totalStages - 1; i++) {
      sum += svgDistribution[i];
      stageStartIndices.add(sum);
    }

    // 创建SVG图标
    List<Widget> svgIcons = [];

    // 遍历创建每个SVG图标
    for (int i = 0; i < totalSvgCount; i++) {
      // 计算角度（从左到右，π到0）
      final double angle = pi - i * (pi / (totalSvgCount - 1));

      // 计算SVG中心点的位置
      final double iconCenterX = centerX + radius * cos(angle);
      final double iconCenterY = radius * (1 - sin(angle)) + 30.w;

      // 计算旋转角度
      final double rotationAngle = -angle + pi / 2;

      // 确定这个SVG属于哪个阶段（从左到右）
      int stageIndex = 0;
      for (int j = 0; j < totalStages; j++) {
        int startIdx = j == 0 ? 0 : stageStartIndices[j];
        int endIdx = j == totalStages - 1
            ? totalSvgCount - 1
            : stageStartIndices[j + 1] - 1;

        if (i >= startIdx && i <= endIdx) {
          stageIndex = j;
          break;
        }
      }

      // 获取当前阶段的颜色
      Color stageColor = stageColors[stageIndex % stageColors.length];

      // 判断是否激活（currentStage从1开始，stageIndex从0开始）
      bool isActive = stageIndex < currentStage;

      // 添加SVG图标
      svgIcons.add(Positioned(
        left: iconCenterX - svgWidth / 2,
        top: iconCenterY - svgHeight / 2,
        child: Transform.rotate(
          angle: rotationAngle,
          child: SvgPicture.asset(
            Assets.testSemiCircleProgress,
            width: svgWidth,
            height: svgHeight,
            colorFilter: ColorFilter.mode(
              isActive ? stageColor : inactiveColor,
              BlendMode.srcIn,
            ),
          ),
        ),
      ));
    }

    return SizedBox(
      width: size.width,
      height: size.height,
      child: Stack(
        children: svgIcons,
      ),
    );
  }

  // 计算每个阶段应该分配的SVG数量
  List<int> _calculateSvgDistribution(int stages, int totalSvgs) {
    List<int> distribution = [];

    // 所有情况统一使用相同的计算逻辑
    int baseSvgCount = totalSvgs ~/ stages;
    int remainder = totalSvgs % stages;

    for (int i = 0; i < stages; i++) {
      if (i < remainder) {
        distribution.add(baseSvgCount);
      } else {
        distribution.add(baseSvgCount + 1);
      }
    }

    return distribution;
  }
}
